<template>
  <el-dialog v-model="dialogInfo.visible" :title="dialogInfo.title" :width="dialogInfo.width" align-center>
    <el-form label-width="120px">
      <el-form-item label="上传文件" prop="file">
        <el-upload class="upload-demo" ref="uploadBinRef" action :http-request="uploadBins" :file-list="fileListBin" :auto-upload="false">
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="info" plain @click="onCancel()">关闭</el-button>
        <el-button type="primary" @click="onSubmit()">上传到服务器</el-button>

      </span>
    </template>
  </el-dialog>
</template>

<script setup>
/**
 * 管理员编辑组件
 */
import { ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import EsAjax from '@/utils/EsAjax';
import ApiUrls from '@/apis/index';
import { roleParams } from '@/apis/model/RoleModel';
import { getNewObj } from '@/utils/EsCommon';

// ======================================================
//                      变量声明
// ======================================================

// emit
const emit = defineEmits(['success']);
// 弹窗信息
const uploadBinRef = ref(null)
const dialogInfo = ref({
  visible: false,
  title: '',
  width: '600px',
})
// 表单组件的引用实例
const fileListBin = ref([])
const binId = ref('')

// ======================================================
//                      点击操作
// ======================================================
 

// 点击取消按钮
const onCancel = () => {
  dialogInfo.value.visible = false;
}
// ======================================================
//                      处理事件
// ======================================================

// 加载数据
const show = async (id, title, item = null, width = '600px') => {
  dialogInfo.value.title = title;
  dialogInfo.value.width = width;
  dialogInfo.value.visible = true;
  fileListBin.value = []
  binId.value = id
}



// 点击提交按钮
const onSubmit = () => {
  uploadBinRef.value.submit();
}





const uploadBins = (file) => {

  console.log('file', file)
  const formData = new FormData();
  formData.append("file", file.file);
  formData.append("system", "");
  formData.append("ftype", "bin");
  formData.append("rid", Number(binId.value));
  const xhr = new XMLHttpRequest();
  xhr.open("post", "/api/file/upload", true);
  xhr.setRequestHeader("Authorization", localStorage.Authorization);
  xhr.onload = (res) => {
    var json = JSON.parse(xhr.responseText);
    if (json.code == 200) {
      ElMessage.success("上传成功");
      dialogInfo.value.visible = false;
      emit('success');
    } else {
      fileListBin.value = []
      ElMessage.error(json.msg)

    }
  };
  xhr.onerror = () => {
    //console.log('上传失败');
  };
  xhr.ontimeout = function timeout() {
    //console.log('上传超时，请刷新重试');
  };
  xhr.send(formData);
  // //console.log(json)
}


defineExpose({
  show
})
</script>

<style scoped>
</style>
